
/**
 * Created by wangjiakun on 2018/3/19 0019.
 */
import React from 'react';
import {connect} from 'react-redux';

import { messages, getApprovelHistory } from 'share/common';
import {
  Input,
  Form,
  DatePicker,
  Divider,
  Checkbox,
  message,
  Tabs,
  Row,
  Col,
  Affix,
  Spin,
  Modal,
  Button,
  Select
} from 'antd';
const FormItem = Form.Item;
const TextArea = Input.TextArea;
const TabPane = Tabs.TabPane;
const Option = Select.Option;
const confirm = Modal.confirm;

import moment from 'moment';
import debounce from 'lodash.debounce'
import travelService from 'containers/request/travel-request/travel.service'
import travelUtil from 'containers/request/travel-request/travelUtil'
import baseService from 'share/base.service' ;
import TravelLocation from 'containers/request/travel-request/comp/location'
import TravelPrompt from 'containers/request/travel-request/travel-prompt'

class TravelSubsidy extends React.Component {
  startDate = "";
  endDate = "";
  baseDays = 0;//如果没有携带默认值则显示最大天数。
  currentCity = {city: null, isChange: false};
  profile = {};
  baseStartDate = "";
  baseEndDate = "";

  constructor(props) {
    super(props);
    this.state = {
      isEditing: false,//是否是编辑状态
      isLoading: false,
      days: 1,//区间天数
      cityResult: [],
      params: {},
      formCtrl: {},
      standardEnable: false,
      promptList: [], //行程提示语的配置
      baseIsShowCity: true, //是否展示城市控件 reset的时候使用
      isShowCity: true, //是否展示城市控件
      isDefaultAll: false, //是否默认全选
      isSelectAll: false, //是否全选差补费用
      isGetType: false,//是否在获取差补类型
      subsidyTypeData: [],//获取的对应城市的差补类型
      allSubsidyData: {},//根据城市返回的差补类型的所有数据
      isNeedInitExpense: true //初次打开slide，是否需要更新差补费用类型
    };
  };

  componentWillMount() {
    let tempMap = this.props.params['travelInfo']['customFormPropertyMap'];
    let isStandard = tempMap['ca.travel.applypolicy.enable'] ? JSON.parse(tempMap['ca.travel.applypolicy.enable']) : false;
    let promptList = tempMap['travel.itinerary.tips'] ? JSON.parse(tempMap['travel.itinerary.tips']) : [];
    let dimension = tempMap['travel.subsidies.dimension'] ? JSON.parse(tempMap['travel.subsidies.dimension']) : null;
    let startDate = travelUtil.getFormHeadValue(this.props.params.defaultValue, 'start_date');
    let endDate = travelUtil.getFormHeadValue(this.props.params.defaultValue, 'end_date');
    let days = 0;
    let isDefaultAll = dimension && dimension.subsidySelection;
    let isShowCity = dimension && dimension.defaultDimensions && dimension.defaultDimensions.indexOf('ALLOWANCE_CITY') >= 0;
    if (startDate && endDate) {
      days = travelUtil.calculateDate(startDate, endDate);
      this.baseDays = days;
    }
    this.setState({
      promptList,
      params: this.props.params,
      standardEnable: isStandard,
      isDefaultAll: isDefaultAll,
      isShowCity: isShowCity,
      baseIsShowCity: isShowCity,
      days: days
    });
    baseService.getProfile().then(res=> {
      this.profile = res.data;
    });
    this.setDate();
  };

  setDate = () => {
    this.baseStartDate = travelUtil.getFormHeadValue(this.props.params.defaultValue, 'start_date');
    this.baseEndDate = travelUtil.getFormHeadValue(this.props.params.defaultValue, 'end_date');
    let days = travelUtil.calculateDate(this.baseStartDate, this.baseEndDate);
    this.baseDays = days;
    this.startDate = travelUtil.getFormHeadValue(this.props.params.defaultValue, 'start_date');
    this.endDate = travelUtil.getFormHeadValue(this.props.params.defaultValue, 'end_date');
    this.setState({days:days});
  };

  componentWillReceiveProps(nextProps) {
    if(this.props.params.isResetSubsidy){
      this.resetForm();
      delete this.props.params.isResetSubsidy;
      return;
    }
    let editData = travelUtil.isEmpty(this.props.params.editSubsidy);
    if (!editData.isEmpty && !this.state.isEditing) {
      this.setState({isEditing: true});
      this.currentCity.vendorAlias = editData.cityName;
      this.currentCity.code = editData.cityCode;
      this.setHavedCity();//设置默认城市
      let days = travelUtil.calculateDate(editData.startDate, editData.endDate);
      let values = {};
      values.applicationOID = this.props.params.oid;
      values.cityCode = editData.cityCode;
      values.cityName = editData.cityName;
      values.startDate = editData.startDate;
      this.endDate = moment(editData.endDate);
      this.startDate = moment(editData.startDate);
      values.id = editData.id;
      values.endDate = editData.endDate;
      if (editData.expenseTypeOIDs) {
        values.expenseTypeOIDs = editData.expenseTypeOIDs;
      }
      if (editData.expenseTypes.length > 0) {
        editData.expenseTypes.map(item => {
          if (editData.expenseTypeOIDs) {
            if (editData.expenseTypeOIDs.indexOf(item.expenseTypeOID) !== -1) {
              item.isChecked = true;
            } else {
              item.isChecked = false;
            }
          } else {
            //没有已选中的费用类型，说明是初始化状态，默认是否全选读配置
            item.isChecked = this.state.isDefaultAll;
          }
        });
      }
      this.setState({
        subsidyTypeData: editData.expenseTypes.length > 0 ? JSON.parse(JSON.stringify(editData.expenseTypes)) : [],
        allSubsidyData: JSON.parse(JSON.stringify(editData)),
        isEditing: true,
        isShowCity: !!editData.cityCode, //编辑的时候城市是否必填看之前的数据是否有城市数据
        days: days
      },()=>{
        this.props.form.resetFields();
        this.judgeIsSelectAll();
      });
    } else {
      let tempStartDate = travelUtil.getFormHeadValue(this.props.params.defaultValue, 'start_date');
      let tempEndDate = travelUtil.getFormHeadValue(this.props.params.defaultValue, 'end_date');
      if(this.baseStartDate !== tempStartDate || this.baseEndDate !== tempEndDate){//头部时间是否已经改变
        this.setDate();//
      }
      //在这根据城市必填刷新下差补费用类型，注意避免死循环
      if (nextProps && nextProps.params && nextProps.params.isOpenSlide && !this.state.isShowCity && this.state.isNeedInitExpense) {
        this.setState({isNeedInitExpense: false});
        this.initExpenseType();
      }
    }
  };

  initExpenseType = () => {
    let params = {};
    params.applicationOID = this.props.params.oid;
    params.startDate = this.baseStartDate;
    params.endDate = this.baseEndDate;
    this.setState({isGetType: true});
    travelService.requestSubsidyType(params).then(res => {
      if (res.data.expenseTypes.length > 0) {
        res.data.expenseTypes.map(item => {
          item.isChecked = this.state.isDefaultAll;
        })
      }
      this.setState({
        subsidyTypeData: res.data.expenseTypes.length > 0 ? res.data.expenseTypes : [],
        allSubsidyData: res.data
      }, () => {
        this.judgeIsSelectAll();
      });
      this.setState({isGetType: false});
    }).catch(e => {
      this.setState({isGetType: false});
      message.error(messages('request.key190'/*操作失败:*/) + e.response.data.message);
    });
  };

  cfo = travelUtil.createFormOption;

  //重置表单
  resetForm = () =>{
    this.currentCity = {vendorAlias: null, isChange: false};
    this.props.form.resetFields();
    this.setDate();
    delete this.props.params.editSubsidy;
    this.setState({
      isLoading: false,
      isEditing: false,
      isSelectAll: false,
      isShowCity: this.state.baseIsShowCity,
      subsidyTypeData: [],
      cityResult: [],
      days: this.baseDays,
      isNeedInitExpense: true
    });
  }

  //关闭清空所有设置
  closeSubsidy = () => {
    this.props.close();
  };

  //确定差补
  toSubmit = () => {
    this.props.form.validateFieldsAndScroll((err, values) => {
      if(values.remark && values.remark.length === 201){
        message.error(messages('request.key349'/*备注长度超出*/));
        return;
      }
      if (!err) {
        if(!this.state.isEditing && this.state.isShowCity && !this.currentCity.code){
          message.error(messages('request.key395'/*城市不匹配*/));
          return ;
        }
        values.cityCode = this.currentCity ? this.currentCity.code : '';
        values.cityName = this.currentCity ? this.currentCity.vendorAlias : '';
        // values.startDate = values.startDate.utc().format();// 设置开始日期
        // values.endDate = values.endDate.utc().format();//设置结束日期
        // wjk change 2018 08 01 传UTC格式，但后台需要的时分时间日期之间间隔必须是整天（两日期时间差必须是24小时整倍数）
        values.startDate = travelUtil.getAfterDate(-1,values.startDate.local().format("YYYY-MM-DD"))+'T16:00Z';
        values.endDate = travelUtil.getAfterDate(-1,values.endDate.local().format("YYYY-MM-DD"))+'T16:00Z';
        let expenseTypeOIDs = [];
        this.state.subsidyTypeData.map(item=> {
          if (item.isChecked) {
            expenseTypeOIDs.push(item.expenseTypeOID);
          }
        });
        if(!expenseTypeOIDs.length){
          if(this.state.subsidyTypeData.length){
            message.error(messages('request.key396'/*请选择差补类型*/));
          }else{
            message.error(messages('request.key397'/*当前城市无合适差补类型*/));
          }
          return ;
        }
        this.setState({isLoading: true});
        values.expenseTypeOIDs = expenseTypeOIDs;//设置所添加差补类型的oid
        values.applicationOID = this.props.params.oid;//设置申请单oid
        values.travelSubsidiesRequestOID = this.state.allSubsidyData.travelSubsidiesRequestOID;//设置差补id
        values.id = this.state.allSubsidyData.id;//设置id
        values.status = this.state.allSubsidyData.status;//设置状态 1001:初始状态 ，1002:已确认，并生成明细
        values.deleted = this.state.allSubsidyData.deleted;// false or true 表示啥文档没写？
        if (!this.state.isEditing) {//不是编辑状态属于新建提交
          travelService.travelSubsidySubmit(values).then(res=> {
            message.success(messages('request.key189'/*已保存*/));
            this.closeSubsidy();
          }).catch(err=> {
            message.error(err.response.data.message);
            this.setState({isLoading: false});
          })
        } else {
          travelService.updateSubsidy(values).then(res=> {
            message.success(messages('request.key353'/*已更新*/));
            this.closeSubsidy();
          }).catch(err=> {
            this.setState({isLoading: false});
            message.error(messages('request.key190'/*操作失败:*/) + err.response.data.message);
          })
        }
      }
    })
  };

  // 选择 城市 -->获取差补类型
  getSubsidyType = (cityObj) => {
    this.currentCity.isChange = false;
    this.props.form.validateFieldsAndScroll((err, values)=> {
      if (!err) {
        if (this.state.isEditing) {//如果是编辑必填id
          values.id = this.props.params.editSubsidy.id
        }
        if (!this.currentCity.vendorAlias) {
          this.setState({isGetType: true});
          values.applicationOID = this.props.params.oid;
          values.cityCode = cityObj.code;
          values.cityName = cityObj.vendorAlias;
          this.currentCity = cityObj;
          travelService.requestSubsidyType(values).then(res => {
            if (res.data.expenseTypes.length > 0) {
              res.data.expenseTypes.map(item => {
                item.isChecked = this.state.isDefaultAll;
              })
            }
            this.setState({
              subsidyTypeData: res.data.expenseTypes.length > 0 ? res.data.expenseTypes : [],
              allSubsidyData: res.data,
            }, () => {
              this.judgeIsSelectAll();
            });
            this.setState({isGetType: false});
          }).catch(e => {
            this.setState({isGetType: false});
            message.error(messages('request.key190'/*操作失败:*/) + e.response.data.message);
          })
        } else if (this.state.subsidyTypeData && this.currentCity.vendorAlias && this.currentCity.code !== cityObj.code) {
          this.showConfirm(values, cityObj);
        }
      }
    })
  };

  //城市不必填的时候刷新差补规则
  refreshSubsidy = () => {
    this.props.form.validateFieldsAndScroll((err, values)=> {
      if (!err) {
        if (this.state.isEditing) {//如果是编辑必填id
          values.id = this.props.params.editSubsidy.id
        }
        this.showConfirm(values);
      }
    });
  };

  setHavedCity = ()=> {
    if(!this.currentCity.vendorAlias){//是否当前没有选择城市
      this.props.form.resetFields();
      return;
    }
    let citys = [this.currentCity];
    this.setState({cityResult: citys});
    if (this.props.form.getFieldValue("cityName") !== undefined) {
      this.props.form.setFieldsValue({'cityName': citys[0].vendorAlias});
    }
  };

  toggleAllSubsidyType = () => {
    this.setState({
      isSelectAll: !this.state.isSelectAll
    }, () => {
      let temp = this.state.subsidyTypeData;
      temp.map(item => {
        item.isChecked = this.state.isSelectAll;
      });
      this.setState({subsidyTypeData: temp});
    });
  };

  judgeIsSelectAll = () => {
    let isSelectAll = true;
    let temp = this.state.subsidyTypeData;
    temp.map(item => {
      if (!item.isChecked) {
        isSelectAll = false;
      }
    });
    this.setState({
      isSelectAll: isSelectAll
    });
  };

  //选择差补类型
  selectSubsidyType = (index) => {
    let temp = this.state.subsidyTypeData;
    temp[index].isChecked = !temp[index].isChecked;
    this.setState({subsidyTypeData: temp}, () => {
      this.judgeIsSelectAll();
    });
  };

  //时间改变重新计算日期区间天数
  startDateChange = (e) => {
    this.startDate = e;
    let days = 0;
    days = travelUtil.calculateDate(e, this.endDate);
    this.setState({days: days});
  }

  //时间改变重新计算日期区间天数
  endDateChange = (e) => {
    this.endDate = e;
    let days = 0;
    days = travelUtil.calculateDate(this.startDate, e);
    this.setState({days: days});
  }

  disabledDateStart = (current) => {
    let boo = false;
    let startDate = moment(travelUtil.getFormHeadValue(this.props.params.defaultValue, 'start_date'));
    let endDate = travelUtil.getAfterDate(1, moment(this.endDate).format('YYYY-MM-DD'));
    if (current < moment(startDate, 'YYYYMMDD') ||
      current >= moment(endDate, 'YYYYMMDD hh:mm:ss')) {
      boo = true;
    }
    return current && boo;
  };

  disabledDateEnd = (current) => {
    let boo = false;
    let endDate = travelUtil.getFormHeadValue(this.props.params.defaultValue, 'end_date');
    endDate = travelUtil.getAfterDate(1, moment(endDate).format('YYYY-MM-DD'));
    if(!(this.startDate instanceof moment)){
      this.startDate = moment(this.startDate);
    }
    if (current < moment(this.startDate, 'YYYYMMDD') || current >= moment(endDate, 'YYYYMMDD hh:mm:ss')) {
      boo = true;
    }
    return current && boo;
  };

  render() {
    const {isLoading, days, cityResult, isGetType, subsidyTypeData, isSelectAll, isShowCity, promptList} = this.state;
    const {getFieldDecorator} = this.props.form;
    const formItemLayoutL = {
      labelCol: {span: 4},
      wrapperCol: {span: 18}
    };
    const formItemLayoutM = {
      labelCol: {span: 4},
      wrapperCol: {span: 6}
    };
    const formItemLayoutS = {
      labelCol: {span: 8},
      wrapperCol: {span: 12}
    };
    let editData = travelUtil.isEmpty(this.props.params.editSubsidy);
    let isEmpty = editData.isEmpty;
    return (
      <div className="add-subsidy">
        <Spin spinning={isLoading}>
          <TravelPrompt promptList={promptList} type={1006} />
          <Form>
            {isShowCity && (
              <FormItem {...formItemLayoutM} label={messages('request.key400'/*差补城市*/)}>
                {
                  getFieldDecorator('cityName', this.cfo(messages('request.key400'/*差补城市*/), {type: 'str', value: isEmpty ? "" : editData.cityName}))(
                    <TravelLocation intEnable={true}
                                    vendorType="standard"
                                    isEntity={false}
                                    onSelect={this.getSubsidyType}
                                    isOldDataType={true}/>
                  )
                }
              </FormItem>
            )}
            <Row>
              <Col span={12}>
                <FormItem {...formItemLayoutS} label={messages('request.key401'/*开始日期*/)}>
                  {getFieldDecorator('startDate', this.cfo(messages('request.key401'/*开始日期*/),
                    {
                      type: 'moment',
                      value: isEmpty ? this.baseStartDate : editData.startDate
                    }, false))(
                    <DatePicker style={{width:'100%'}} onChange={this.startDateChange} disabledDate={this.disabledDateStart}/>
                  )}
                </FormItem>
              </Col>
              <Col span={2} className="subsidy-days">{messages('request.key471',{arg1:days}/*{arg1}天*/)}</Col>
              <Col span={10}>
                <FormItem {...formItemLayoutS} label={messages('request.key402'/*结束日期*/)}>
                  {
                    getFieldDecorator('endDate', this.cfo(messages('request.key402'/*结束日期*/),
                      {
                        type: 'moment',
                        value: isEmpty ? this.baseEndDate : editData.endDate
                      }, false))(
                      <DatePicker onChange={this.endDateChange} disabledDate={this.disabledDateEnd}/>
                    )
                  }
                </FormItem>
              </Col>
            </Row>
            <Divider></Divider>
            <FormItem label={messages('request.key403'/*差补类型*/)} {...formItemLayoutL}>
              <Spin spinning={isGetType}>
                {
                  subsidyTypeData.length > 0 && (
                    <div style={{position: 'relative'}}>
                      <Checkbox checked={isSelectAll} onClick={()=>this.toggleAllSubsidyType()}>{messages('request.key404'/*全选*/)}</Checkbox>
                      {!isShowCity && <Button style={{position: 'absolute', right: '0px'}} size="small" onClick={this.refreshSubsidy}>{messages('request.key562')/*刷新差补规则*/}</Button>}
                    </div>
                  )
                }
                {
                  subsidyTypeData.length > 0 ? <Row>
                      {
                        subsidyTypeData.map((item, index)=> {
                          return (
                            <div className="" style={{float: 'left', marginRight: 32}} onClick={()=>this.selectSubsidyType(index)}
                                 key={item.iconName+index}>
                              <Checkbox checked={item.isChecked} className=""></Checkbox>
                              <span style={{cursor: 'pointer'}}>{item.name}</span>
                            </div>
                          )
                        })
                      }
                    </Row> : <div style={{position: 'relative'}}>
                      <span>{messages('request.key397'/*当前城市无合适差补类型*/)}</span>
                      {!isShowCity && <Button style={{position: 'absolute', right: '0px', top: '4px'}} size="small" onClick={this.refreshSubsidy}>{messages('request.key562')/*刷新差补规则*/}</Button>}
                    </div>
                }
              </Spin>
            </FormItem>
            <Divider></Divider>
            <FormItem {...formItemLayoutL} label={messages('request.key364'/*备注*/)}>
              {
                getFieldDecorator('remark', this.cfo(messages('request.key364'/*备注*/), {type: 'str', value: editData.remark}, true))(
                  <TextArea style={{marginTop:12}} autosize={{minRows: 3, maxRows: 6}} maxLength="201"/>
                )
              }
            </FormItem>
          </Form>
        </Spin>
        <Affix className="travel-affix" offsetBottom={0}>
          <Button type="primary" loading={isLoading} onClick={this.toSubmit}>{messages('request.key211'/*确定*/)}</Button>
          <Button className="travel-type-btn" onClick={this.closeSubsidy}>{messages('request.key175'/*取消*/)}</Button>
        </Affix>
      </div>
    )
  }

  showConfirm = (values, cityObj) => {
    confirm({
      title: messages('request.key173'/*提示*/),
      content: this.state.isShowCity ? messages('request.key405'/*更改城市将清空已添加的差补.*/) : messages('request.key556')/*刷新费用将会清空差补*/,
      okText: messages('request.key211'/*确定*/),
      cancelText: messages('request.key175'/*取消*/),
      onOk: ()=> {
        this.currentCity = cityObj ? cityObj : {};
        this.currentCity.isChange = false;
        this.setState({isGetType: true});
        cityObj && this.setHavedCity();
        values.applicationOID = this.props.params.oid;
        values.cityCode = cityObj ? cityObj.code : '';
        values.cityName = cityObj ? cityObj.vendorAlias : '';
        travelService.requestSubsidyType(values).then(res=> {
          if (res.data.expenseTypes.length > 0) {
            res.data.expenseTypes.map(item=> {
              item.isChecked = this.state.isDefaultAll;
            })
          }
          this.setState({
            subsidyTypeData: res.data.expenseTypes.length > 0 ? res.data.expenseTypes : [],
            allSubsidyData: res.data,
          }, () => {
            this.judgeIsSelectAll();
          });
          this.setState({isGetType: false});
        }).catch(e => {
          this.setState({isGetType: false});
          message.error(messages('request.key190'/*操作失败:*/) + `${e.response.data.message}`);
        })
      },
      onCancel: () => {
        cityObj && this.setHavedCity();
      },
    });
  }

}

function mapStateToProps(state) {
  return { language: state.main.language };
}

const wrappedTravelSubsidy = Form.create()(TravelSubsidy);

export default connect(mapStateToProps)(wrappedTravelSubsidy);
